package com.app.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.app.model.Menu;
import com.app.model.Role;
import com.app.model.RoleMenu;
import com.app.resp.RoleResponse;
import com.app.service.MenuService;
import com.app.service.RoleMenuService;
import com.app.service.RoleService;

@Controller
@RequestMapping("/web/role")
public class RoleController {
	@Resource
	private RoleService roleService;
	@Resource
	private RoleMenuService roleMenuService;
	@Resource
	private MenuService menuService;
	@Resource
	private RoleQuery roleQuery;

	@RequestMapping(value = "")
	public String index() {
		return "auth/role";
	}

	@RequestMapping("/list")
	@ResponseBody
	public Object getList(HttpServletRequest request) {
		return roleQuery.queryPage(roleQuery.getParams(request));
	}

	@RequestMapping("/getRelativeMenuList")
	@ResponseBody
	public Object getRelativeMenuList(Long roleId) {
		List<RoleResponse> result = new ArrayList<RoleResponse>();
		List<Long> checkedlist = roleMenuService.getMenuIdList(roleId);
		List<Menu> list = menuService.findAllByTree();
		for(Menu m:list){
			RoleResponse vo = new RoleResponse();
			vo.setId(m.getId());
			if(m.getpId() ==  null){
				vo.setpId((long)0);
			}else{
				vo.setpId(m.getpId());
			}
			if(checkedlist.contains(m.getId())){
				vo.setChecked(true);
			}
			vo.setName(m.getName());
			result.add(vo);
		}
        return result;
	}
	
	@RequestMapping("/updateRelativeMenu")
	@ResponseBody
	public Object updateRelativeMenu(String checked,String unchecked,Long roleId){
		String msg = "";
		try{
			roleMenuService.update(checked.split(","), unchecked.split(","), roleId);
		}catch(Exception e){
			msg= "更新失败";
		}
		return msg;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Object save(Role role) {
		String msg = null;
		try {
			roleService.save(role);
		} catch (Exception e) {
			msg = "新增权限出错";
		}
		return msg;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Object update(Role role) {
		String msg = null;
		try {
			roleService.update(role);
		} catch (Exception e) {
			msg = "更新权限出错";
		}
		return msg;
	}

	@RequestMapping("/getById")
	@ResponseBody
	public Object getById(Long id) {
		return roleService.getById(id);
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(Long id) {
		String msg = null;
		try {
			roleService.delete(id);
		} catch (Exception e) {
			msg = "删除权限出错";
		}
		return msg;
	}
}
